package com.dingpeikeji.quickdeer.modules.base.service;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.dingpeikeji.quickdeer.modules.base.dao.SendSmsDao;
import com.dingpeikeji.quickdeer.modules.base.entity.TmpSms;
import com.dingpeikeji.quickdeer.modules.sms.entity.Sms;
import com.dingpeikeji.quickdeer.modules.sms.service.SmsApi;

@Service
@Lazy(false)
public class SendSmsTask {
	private Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	private SendSmsDao sendSmsDao;

	@Scheduled(cron = "0 0/5 * * * ?")
	@Transactional(readOnly=false)
	public void execute() {
		List<TmpSms> list = sendSmsDao.select();
		for(TmpSms sms : list) {
			// 发短信给用户
			Sms sendSms = new Sms();
			sendSms.setMobile(sms.getMobile());
			sendSms.setContent(sms.getContent());
			try {
				SmsApi.sendSms(sendSms);
				sendSmsDao.deleteById(sms.getMessageid());
				logger.debug("已发短信：手机号="+sms.getMobile());
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
